<style scoped>
.layout{
    border: 1px solid #d7dde4;
    background: #f5f7f9;
    position: relative;
    border-radius: 4px;
    overflow: hidden;
}
.layout-logo{
    float: left;
    position: relative;
    top: 8px;
    left: 20px;
}
.layout-logo img{
    width: 120px
}
.layout-nav{
    width: 420px;
    margin: 0 auto;
    margin-right: 20px;
}

.ivu-layout-header{
    background-color: #fff;
}
 .ivu-menu-vertical.ivu-menu-light:after {
    content: '';
    display: block;
    width: 1px;
    height: 100%;
    background: #fff;
    position: absolute;
    top: 0;
    bottom: 0;
    right: 0;
    z-index: 1;
}
</style>
<template>
    <div class="layout">
        <Layout>
            <Header>
                 <!-- <Row> -->
                     <!-- <Col :lg="22" :md="22" :sm='22' :xs="22"> -->
                    <div class="layout-logo">
                        <router-link to="/">
                            <img src="https://happychuan.oss-cn-shenzhen.aliyuncs.com/web/logo.png" alt="logo">
                        </router-link>
                    </div>
                     <!-- </Col> -->
                        <!-- <Col :lg="2" :md="2" :sm='2' :xs="2"> -->
                        <Menu style="float:right;margin-right:20px" @on-select="onSelect">
                            <Dropdown trigger="click" style="float:right;" >
                                 {{username}}
                            <a href="javascript:void(0)">
                                <Avatar :src="baseUrl + this.$store.state.Avatar" />
                            </a>
                            <DropdownMenu slot="list">
                                <DropdownItem>
                                    <MenuItem name="profile" >
                                        <Icon type="ios-person" />
                                            个人主页
                                    </MenuItem> 
                                </DropdownItem>
                                <DropdownItem>
                                    <MenuItem name="logout"  >
                                        <Icon type="md-power" />
                                            退出
                                    </MenuItem> 
                                </DropdownItem>
                            </DropdownMenu>
                        </Dropdown>
                    </Menu>
                    <!-- </Col> -->
                    <!-- <Col :lg="0" :md="0" :sm='0' :xs="4">
                    111
                    </Col> -->
                    <!-- </Row> -->
            </Header>
            <Layout>
                <!-- <Row > -->
                     <!-- <Col :lg="4" :md="4" :sm='4' :xs="0"> -->
                <Sider hide-trigger :style="{background: '#fff'}">
                    <Menu :active-name="$route.path"  width="auto" :open-names="[$route.path.split('/')[1]]" :accordion='true' >
                        <Submenu name="1">
                             <template slot="title">
                                <Icon type="ios-analytics"></Icon>
                                总体概况
                            </template>
                            <MenuItem name="/admin" to='/admin'>总体分析</MenuItem>
                        </Submenu>
                        <Submenu name="create">
                            <template slot="title">
                                <Icon type="ios-keypad"></Icon>
                                创作
                            </template>
                            <MenuItem name="/create/article" to='/create/article'>文章编写</MenuItem>
                            <MenuItem name="/create/saying" to='/create/saying'>语录编写</MenuItem>
                        </Submenu>
                        <Submenu name="manage">
                            <template slot="title">
                                <Icon type="ios-navigate"></Icon>
                                管理
                            </template>
                            <MenuItem name="/manage/article" to='/manage/article'>文章管理</MenuItem>
                            <MenuItem name="/manage/saying" to='/manage/saying'>语录管理</MenuItem>
                            <MenuItem name="/manage/user" to='/manage/user'>用户管理</MenuItem>
                            <MenuItem name="/manage/link" to='/manage/link'>友链管理</MenuItem>
                        </Submenu>
                    </Menu>
                </Sider>
                <!-- </Col> -->
                 <!-- <Col :lg="20" :md="20" :sm='20' :xs="24"> -->
                <Layout :style="{padding: '16px 16px 24px'}">
                    <!-- <Breadcrumb :style="{margin: '5px 0'}">
                        <BreadcrumbItem>Home</BreadcrumbItem>
                        <BreadcrumbItem>Components</BreadcrumbItem>
                        <BreadcrumbItem>Layout</BreadcrumbItem>
                    </Breadcrumb> -->
                    <Content :style="{padding: '16px', minHeight: '560px', background: '#fff'}">
                        <router-view></router-view>
                    </Content>
                </Layout>
                <!-- </Col> -->
                <!-- </Row> -->
            </Layout>
        </Layout>
         <div>
            <Drawer
                title="个人主页"
                v-model="value3"
                width="520"
                :mask-closable="false"
                :styles="styles"
            > 
            <Badge color="blue" :text="username" /> <Tag color="red">{{isAdmin}}</Tag>
            <Divider orientation="left">头像更换</Divider>
            <div  style="display: inline-block;width:58px;height:60px;margin-right:20px">
                <img :src="baseUrl + this.$store.state.Avatar" alt="头像" style="width:58px;height:60px">
            </div>
            <Upload
                ref="upload"
                :show-upload-list="false"
                :on-success="handleSuccess"
                :format="['jpg','jpeg','png']"
                :max-size="2048"
                :on-format-error="handleFormatError"
                :on-exceeded-size="handleMaxSize"
                :before-upload="handeleBeforeUpload"
                type="drag"
                accept="image/*"
                action=" "
                style="display: inline-block;width:58px;">
                <div style="width: 58px;height:58px;line-height: 58px;">
                    <Icon type="ios-camera" size="20"></Icon>
                </div>
            </Upload>
            <Divider orientation="left">密码修改</Divider>
            <Form ref="formInline" :model="formInline" :rules="ruleInline" inline>
                <FormItem prop="password1">
                    <Input type="password" v-model="formInline.password1" placeholder="请输入新密码">
                        <Icon type="ios-lock-outline" slot="prepend"></Icon>
                    </Input>
                </FormItem>
                <FormItem prop="password2">
                    <Input type="password" v-model="formInline.password2" placeholder="请再次输入密码">
                        <Icon type="ios-lock-outline" slot="prepend"></Icon>
                    </Input>
                </FormItem>
                <FormItem>
                    <Button type="primary" @click="updatePsw('formInline')">修改密码</Button>
                </FormItem>
            </Form>
            <Divider orientation="left">名称修改</Divider>
            <Input v-model="Name" placeholder="限制10个字符"  maxlength="10"/>
            <Button type="primary" @click="updateName" style="margin-top:20px">修改名称</Button>
                <Modal
                    v-model="modal1"
                    title="操作图片"
                    :loading="loading"
                    @on-ok="uploadAvatar">
                    <div class="cropper">
                         <vueCropper
                            ref="cropper"
                            :img="option.img"
                            :outputSize="option.size"
                            :outputType="option.outputType"
                            :info="true"
                            :full="option.full"
                            :canMove="option.canMove"
                            :canMoveBox="option.canMoveBox"
                            :original="option.original"
                            :autoCrop="option.autoCrop"
                            :fixed="option.fixed"
                            :fixedNumber="option.fixedNumber"
                            :centerBox="option.centerBox"
                            :infoTrue="option.infoTrue"
                            :fixedBox="option.fixedBox"
                            @realTime="realTime"
                        ></vueCropper>
                    </div><!--cropper-->
                </Modal>
        </Drawer>
        </div>      
    </div>
</template>
<script>
import { mapMutations } from 'vuex';
import { VueCropper } from "vue-cropper";
    export default {
        data(){
            return{
                modal1: false,
                baseUrl:'',
                Name:'',
                username:'',
                isAdmin:'普通用户',
                value3: false,
                styles: {
                    height: 'calc(100% - 55px)',
                    overflow: 'auto',
                    paddingBottom: '53px',
                    position: 'static'
                },
                 formInline: {
                    password2: '',
                    password1: ''
                },
                ruleInline: {
                    password1: [
                        { required: true, message: 'Please fill in the password', trigger: 'blur' }
                    ],
                    password2: [
                        { required: true, message: 'Please fill in the password.', trigger: 'blur' },
                    ]
                },
               option: {
                    img: '', // 裁剪图片的地址
                    info: true, // 裁剪框的大小信息
                    outputSize: 0.8, // 裁剪生成图片的质量
                    outputType: 'png', // 裁剪生成图片的格式
                    canScale: false, // 图片是否允许滚轮缩放
                    autoCrop: true, // 是否默认生成截图框
                    // autoCropWidth: 300, // 默认生成截图框宽度
                    // autoCropHeight: 200, // 默认生成截图框高度
                    fixedBox: true, // 固定截图框大小 不允许改变
                    fixed: true, // 是否开启截图框宽高固定比例
                    fixedNumber: [1, 1], // 截图框的宽高比例
                    full: true, // 是否输出原图比例的截图
                    canMoveBox: false, // 截图框能否拖动
                    original: false, // 上传图片按照原始比例渲染
                    centerBox: false, // 截图框是否被限制在图片里面
                    infoTrue: true // true 为展示真实输出图片宽高 false 展示看到的截图框宽高
                },
                fileinfo:'',
                // 防止重复提交
                loading: false
            }
        },
        components:{
            VueCropper,
        },
        methods:{
             ...mapMutations(['changeName','changeAvatar','changeLogin']),
            onSelect(name){
                if(name == 'logout'){
                    localStorage.removeItem('Authorization');
                    this.changeAvatar({Avatar:''})
                    this.changeLogin({Authorization:''})
                    this.$router.push('/login');
                }else if(name == 'profile'){
                    this.value3 = true;
                    this.Name = this.$store.state.Name
                }
                
            },
            updatePsw(name){
                 this.$refs[name].validate((valid) => {
                     if(valid){
                         if(this.formInline.password2 != this.formInline.password1){
                             this.$Notice.error({
                                 title: '输入有误',
                                 desc: '两次输入的密码不一样！'
                             });
                             return ;
                         }
                         let that = this
                         this.$axios.post('/api/manage/updatepsw',{password:this.formInline.password1}).then(res =>{
                             if(res.data.err_code == 0){
                                that.$router.push('/login');
                             }else if(res.data.err_code == 1){
                                that.$Notice.success({
                                    title: '修改成功',
                                    desc: `3s后将自动退出登陆！`
                                });
                                setTimeout(()=>{
                                    localStorage.removeItem('Authorization');
                                    that.$router.push('/login');
                                },3000)
                             }else if(res.data.err_code == 4){
                                  that.$Notice.error({
                                        title: '错误',
                                        desc: '参数有误！'
                                });
                             }
                             
                         })
                     }else{
                         this.$Notice.error({
                                title: '错误',
                                desc: '参数有误！'
                        });
                     }
                 })

            },
            updateName(){
                if(this.Name.length < 1){
                    this.$Notice.error({
                        title:'请输入名称！',
                        desc:''
                    })
                    return;
                }
                this.$axios.post('/api/manage/updatename',{name:this.Name}).then(res=>{
                    let that = this;
                     if(res.data.err_code == 0){
                        that.$router.push('/login');
                    }else if(res.data.err_code == 1){
                        that.$Notice.success({
                            title: '修改成功',
                            desc: ` `
                        });
                        that.changeName({Name:this.Name})
                    }else if(res.data.err_code == 4){
                        that.$Notice.error({
                                title: '错误',
                                desc: '参数有误！'
                        });
                    }
                
                })
            },
            init(){
                if(this.$store.state.isAdmin){
                    this.isAdmin = '管理员'
                }
                this.baseUrl = this.$axios.defaults.baseURL
                
            },
            handleFormatError (file) {
                this.$Notice.warning({
                    title: 'The file format is incorrect',
                    desc: 'File format of ' + file.name + ' is incorrect, please select jpg or png.'
                });
            },
            handleMaxSize (file) {
                this.$Notice.warning({
                    title: 'Exceeding file size limit',
                    desc: 'File  ' + file.name + ' is too large, no more than 2M.'
                });
            },
             handleSuccess (res, file) {
                file.url = 'https://o5wwk8baw.qnssl.com/7eb99afb9d5f317c912f08b5212fd69a/avatar';
                file.name = '7eb99afb9d5f317c912f08b5212fd69a';
            },
            handeleBeforeUpload(file){
                this.fileinfo =file
                let data = window.URL.createObjectURL(new Blob([file]));
                this.option.img = data
                this.modal1 = true
                return false;//取消自动上传
            },
            // 实时预览函数
            realTime() {
            },
            uploadAvatar() {
                let that = this
                this.$refs.cropper.getCropBlob((data) => {
                    that.loading = true
                    that.$refs.upload.clearFiles() 
                    let formData=new FormData();
                    formData.append('avatar',data)
                    formData.append('oldAvatar',this.$store.state.Avatar)
                    that.$axios.post('/api/manage/avatar/update',formData,{
                        'Content-Type':'multipart/form-data'
                    }).then(res=>{
                        that.loading = false
                       if(res.data.err_code == 0){
                            that.$router.push('/login')
                        }else if(res.data.err_code == 1){
                            that.$Message.success('修改成功！')
                            that.changeAvatar({Avatar:res.data.data.slice(1)})
                        }else{
                            that.$Message.error('服务器出错！')
                        }
                    
                    })

                })
            },
            
        },
         mounted(){
             this.init()
            var that = this
            this.$axios.post('/api/manage/home').then(res =>{
               if(res.data.err_code == 1){
                   //登陆成功
                   this.username = res.data.data
                }else{
                    localStorage.removeItem('Authorization');
                    that.$router.push('/login');
               }
                
            })

        }
    }
</script>
<style lang="less" scoped>
   // 截图
    .cropper {
        width: auto;
        height: 300px;
    }
</style>


